/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.takeaddrecord.service;

import java.util.List;

import com.jeeplus.modules.centertakeposition.entity.CenterTakePosition;
import com.jeeplus.modules.centertakeposition.service.CenterTakePositionService;
import com.jeeplus.modules.takegoods.entity.TakeGoods;
import com.jeeplus.modules.takegoods.service.TakeGoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.service.CrudService;
import com.jeeplus.modules.takeaddrecord.entity.TakeAddRecord;
import com.jeeplus.modules.takeaddrecord.mapper.TakeAddRecordMapper;

/**
 * 库存添加记录Service
 * @author w
 * @version 2021-11-04
 */
@Service
@Transactional(readOnly = true)
public class TakeAddRecordService extends CrudService<TakeAddRecordMapper, TakeAddRecord> {
	@Autowired
	private CenterTakePositionService centerTakePositionService;
	@Autowired
	private TakeGoodsService takeGoodsService;

	public TakeAddRecord get(String id) {
		return super.get(id);
	}
	
	public List<TakeAddRecord> findList(TakeAddRecord takeAddRecord) {
		return super.findList(takeAddRecord);
	}
	
	public Page<TakeAddRecord> findPage(Page<TakeAddRecord> page, TakeAddRecord takeAddRecord) {
		return super.findPage(page, takeAddRecord);
	}
	
	@Transactional(readOnly = false)
	public void save(TakeAddRecord takeAddRecord) {
		if (takeAddRecord.getIsNewRecord()){
			//查询是否有此库存
			CenterTakePosition centerTakePosition = new CenterTakePosition();
			centerTakePosition.setMember(takeAddRecord.getMember());
			centerTakePosition.setGoods(takeAddRecord.getGoods());
			List<CenterTakePosition> list = centerTakePositionService.findList(centerTakePosition);
			if (list.size() > 0){
				list.get(0).setStock(list.get(0).getStock() + takeAddRecord.getNum());
				centerTakePositionService.save(list.get(0));
			}else {
				//没有添加库存资产
				CenterTakePosition entity = new CenterTakePosition();
				entity.setMember(takeAddRecord.getMember());
				entity.setGoods(takeAddRecord.getGoods());
				entity.setStock(takeAddRecord.getNum());
				centerTakePositionService.save(entity);
			}
			//对应商品库存减少
			TakeGoods takeGoods = takeGoodsService.get(takeAddRecord.getGoods().getId());
			if (takeGoods != null){
				if (takeGoods.getStock() != null){
					takeGoods.setStock(takeGoods.getStock() - takeAddRecord.getNum());
					takeGoodsService.save(takeGoods);
				}
			}
		}
		super.save(takeAddRecord);
	}
	
	@Transactional(readOnly = false)
	public void delete(TakeAddRecord takeAddRecord) {
		super.delete(takeAddRecord);
	}
	
}